package cn.codeforfun.aop;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * Created by Administrator on 2017/2/28.
 */
@Component
@Aspect
public class AopLog {

  public Logger log = Logger.getLogger(getClass());

  @Pointcut("execution(public * cn.codeforfun..*.*(..))")
  public void log() {
  }

  @Before("log()")
  public void before(JoinPoint joinPoint) {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    // 记录下请求内容
    String url = request.getRequestURL().toString();
    String httpMethod = request.getMethod();
    String ip = request.getRemoteAddr();
    String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
    String args = Arrays.toString(joinPoint.getArgs());
    log.info("REQUEST:HTTP_METHOD:" + httpMethod + ",CLASS_METHOD:" + classMethod + ",ARGS:" + args + ",IP:" + ip + ",URL:" + url);
  }

  @AfterReturning(pointcut = "log()", returning = "object")
  public void afterReturning(JoinPoint joinPoint, Object object) {
    // 处理完请求，返回内容
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    String httpMethod = request.getMethod();
    String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
    log.info("RESPONSE : " + object + "-------REQUEST:HTTP_METHOD:" + httpMethod + ",CLASS_METHOD:" + classMethod);
  }
}
